package com.luke.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.luke.springcloud.handler.MyBlockHandler;
import com.luke.springcloud.handler.MyFallbackHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 学习注解@SentinelResource
 */
@RestController
@Slf4j
public class SentinelResourceController {

    //既可以使用url作为资源也可以使用SentinelResource资源名作为限流
    //使用url达到阈值返回默认值，使用资源名则会返回异常信息，
    // 所以需要@SentinelResource制定限流和错误处理器handler
    @GetMapping("/testSR")
    @SentinelResource("testSR")//不支持private级别方法
    public String testSR(){
        log.info("testSR()");
        return "testSR";
    }

    //使用全局blockHandler
    @GetMapping("/blockHandler")
    @SentinelResource(value = "blockHandler",
            blockHandlerClass = MyBlockHandler.class,blockHandler = "myBlockHandler1")
    public String blockHandler(){
        log.info("blockHandler()");
        return "success";
    }

    //使用fallback处理业务异常
    @GetMapping("/fallback/{id}")
    //@SentinelResource(value = "fallback",fallback = "handleFallback")
    @SentinelResource(value = "fallback",
            fallbackClass = MyFallbackHandler.class,fallback = "fallback1",//处理业务逻辑
            blockHandlerClass = MyBlockHandler.class,blockHandler = "myBlockHandler2",//处理sentinel限流、熔断规则
            exceptionsToIgnore = IllegalArgumentException.class)//忽略对某些异常的处理，将不使用fallback处理（异常将往外抛出去）
    // 如果点了出错的接口，又触发了限流规则，那么将交给后者blockHandler处理
    public String fallback(@PathVariable Integer id){
        log.info("fallback()");
        if(id == 2){
            throw new IllegalArgumentException("非法参数值");
        }
        return "success";
    }

    //参数必须和请求方法一致，且不能去掉@PathVariable
    public String handleFallback(@PathVariable Integer id,Throwable throwable){
        return "handleFallback";
    }

}
